<?php
/*  Session.Class.php
 *  Session Manager
 *  @link        http://www.sunboyu.cn
 *  @package     OA
 *  @version     V1.0
 *
 *  2008 08 14  sunboyu@gmail.com
 */
class Session
{
	var $lifetime;
	var $db = true;
	var $table = 'session';
	function Session()
	{
		
	}
	function _init( $config = array() )
	{	
		foreach( $config as $key => $value )
		{
			$this->$key = $value;
		}
	}
	#open
	function open( $savepath , $session_name )
	{
		$this->lifetime =  get_cfg_var("session.gc_maxlifetime");
		return true;
	}
	#close
	function close()
	{
		return true;
	}
	#read
	function read( $session_id )
	{
		$sql = sprintf("SELECT * FROM %s WHERE session_id = %s",$this->table,GetSqlString( $session_id ));
		$result = $this->db->fetch( $sql );
		if($result)
		{
			return $result['session_value'];
		}
		else
		{
			return null;
		}
	}
	#write
	function write( $session_id , $session_value )
	{
		$sql = sprintf("SELECT session_id FROM %s WHERE session_id = %s",$this->table,GetSqlString( $session_id ));
		$result = $this->db->fetch( $sql );
		if(!$result)
		{
			$newsql = sprintf("INSERT INTO %s SET session_id = %s , session_value = %s , session_expires = %d",
				$this->table,
				GetSqlString( $session_id ),
				GetSqlString( $session_value ),
				GetSqlString( $this->lifetime+time() , "int" ));
		}
		else
		{
			$newsql = sprintf("UPDATE %s SET session_value = %s , session_expires = %d WHERE session_id = %s",
				$this->table,
				GetSqlString( $session_value ),
				GetSqlString( $this->lifetime+time() , "int" ),
				GetSqlString( $session_id ));
		}
		return $this->db->query( $newsql );
	}
	#destroy
	function destroy( $session_id )
	{	
		$delsql = sprintf("DELETE FROM %s WHERE session_id = %s",$this->table,GetSqlString( $session_id ));
		return $this->db->query( $delsql );
	}
	#gc
	function gc()
	{
		 $gcsql = sprintf("DELETE FROM %s WHERE session_expires < %d",$this->table,time());
		 return $this->db->query( $gcsql );
	}
}
?>